import { Modal } from "antd";
import { useImperativeHandle, useState } from "react";
import api from "../../../../api";
import type { Order } from "../../../../types/api";
import { message } from "../../../../utils/AntdGlobal";

export default function OrderMarker(props: any) {
    const [visible, setVisible] = useState(false)
    const [orderId, setOrderId] = useState('')
    const [markers, setMarkers] = useState<{ lng: string, lat: string, id: number }[]>([])

    useImperativeHandle(props.ref, () => {
        return {
            open
        }
    })

    const open = async (orderId: string) => {
        setOrderId(orderId)
        setVisible(true)
        const detail = await api.getOrderDetail(orderId)
        renderMap(detail)
    }

    const renderMap = (detail: Order.OrderItem) => {
        const map = new window.BMapGL.Map('markerWrap')
        map.centerAndZoom(detail.cityName, 12)
        const scaleCtrl = new window.BMapGL.ScaleControl();  // 添加比例尺控件
        map.addControl(scaleCtrl);
        const zoomCtrl = new window.BMapGL.ZoomControl();  // 添加缩放控件
        map.addControl(zoomCtrl);
        detail.route?.map(item => {
            createMarker(map, item.lng, item.lat)
        })
        map.addEventListener('click', function (e: any) {
            createMarker(map, e.latlng.lng, e.latlng.lat)
        })
    }

    const createMarker = (map: any, lng: string, lat: string) => {
        const id = Math.random()
        const marker = new window.BMapGL.Marker(new window.BMapGL.Point(lng, lat))
        markers.push({ lng, lat, id })
        marker.id = id
        const markerMenu = new window.BMapGL.ContextMenu()
        markerMenu.addItem(new window.BMapGL.MenuItem('删除', function () {
            map.removeOverlay(marker)
            const index = markers.findIndex(item => item.id === marker.id)
            markers.splice(index, 1)
            setMarkers([...markers])
        }))
        marker.addContextMenu(markerMenu)
        map.addOverlay(marker)
    }
    const handleSubmit = async () => {
        await api.updateOrderInfo({
            orderId,
            route: markers
        })
        handleCancel()
        message.success('打点成功')
    }
    const handleCancel = () => {
        setVisible(false)
        setMarkers([])
    }
    return (
        <Modal
            title='地图打点'
            width={1100}
            open={visible}
            okText='确认'
            cancelText='取消'
            onOk={handleSubmit}
            onCancel={handleCancel}
        >
            <div id="markerWrap" style={{ height: 450 }}></div>
        </Modal>
    )
}